package cn.edu.sdju.wanglo1911.team10.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.edu.sdju.wanglo1911.team10.po.ShoppingCartItem;
import cn.edu.sdju.wanglo1911.team10.po.UserAccount;
import cn.edu.sdju.wanglo1911.team10.service.OrderService;
import cn.edu.sdju.wanglo1911.team10.service.ShoppingCartService;

@Controller
public class ShoppingCartController {
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/shopping-cart")
	public String shoppingCart(HttpServletRequest request, String userId, String bookId, Integer amount,HttpSession session, Model model) {
		
		UserAccount account = (UserAccount) session.getAttribute("account");
		model.addAttribute("account", account);
		
		if ("POST".equals(request.getMethod())) {
			ShoppingCartItem newItem = new ShoppingCartItem();
			newItem.setUserId(userId);
			newItem.setBookId(bookId);
			newItem.setAmount(amount);
			System.out.println(userId);
			if (!shoppingCartService.insertItem(newItem)) {
				model.addAttribute("message", "成功加入购物车");
			}
		}
		
		List<ShoppingCartItem> items = shoppingCartService.getAllItemByUserId(account.getId());
		model.addAttribute("items", items);
		return "shopping-cart";
	}
	@RequestMapping(value = "/order", method = {RequestMethod.POST})
	public String newOrder(HttpServletRequest request, HttpSession session, Model model) {
		UserAccount userAccount = (UserAccount) session.getAttribute("account");
		model.addAttribute("account", userAccount);
		List<ShoppingCartItem> shoppingCartItems = 
				shoppingCartService.getAllItemByUserId(userAccount.getId());
		orderService.createOrder(shoppingCartItems);
		model.addAttribute("message", "订单成功提交");
		return "message";
	}
	
	@RequestMapping(value = "/shopping-cart/delete", method = {RequestMethod.POST})
	public String deleteItem(HttpServletRequest request,String bookId, HttpSession session, Model model) {
		
		UserAccount account = (UserAccount) session.getAttribute("account");
		ShoppingCartItem item = new ShoppingCartItem();
		item.setUserId(account.getId());
		item.setBookId(bookId);
		item = shoppingCartService.getItemById(item);
		shoppingCartService.deleteItem(item);
		return "redirect:/shopping-cart";
	}
	
}
